import React, { useEffect, useState } from 'react';
import { useStore } from '@/store';
import Editor from 'react-simple-code-editor';
import { highlight, languages } from 'prismjs';
import 'prismjs/components/prism-clike.min';
import 'prismjs/components/prism-javascript.min';
import 'prismjs/themes/prism.css';

import styles from './index.less';

const SlideContent = () => {
  const { slideList, currentSlideIndex } = useStore();
  // 单个幻灯片
  const slideListItem = slideList?.[currentSlideIndex - 1] || [];

  const doubleClick = (typeItem, elementsIndex) => {
    document.dispatchEvent(
      new CustomEvent('passEvent', {
        detail: {
          type: typeItem,
          elementsIndex: elementsIndex,
        },
      }),
    );
  };

  // 判断什么语言;python、c、javascript
  const detectLanguage = (code) => {
    // Simple language detection based on common patterns
    const pythonPatterns = [/^#!/, /\bdef\b/, /\bprint\(/, /\bimport\b.*\n/, /:\s*$/m];

    const cPatterns = [
      /#include/,
      /int\s+main\s*\(/,
      /printf\s*\(/,
      /scanf\s*\(/,
      /void\s+\w+\s*\(/,
    ];

    const jsPatterns = [/const\s+/, /let\s+/, /function\s+/, /=>/, /console\.log/];

    let pythonScore = 0;
    let cScore = 0;
    let jsScore = 0;

    pythonPatterns.forEach((pattern) => {
      if (pattern.test(code)) pythonScore++;
    });

    cPatterns.forEach((pattern) => {
      if (pattern.test(code)) cScore++;
    });

    jsPatterns.forEach((pattern) => {
      if (pattern.test(code)) jsScore++;
    });

    if (pythonScore > cScore && pythonScore > jsScore) return 'Python';
    if (cScore > pythonScore && cScore > jsScore) return 'C';
    return 'JavaScript';
  };

  return (
    <div style={{ height: '100%', overflowY: 'auto' }}>
      <div className={styles['slide-content']}>
        {slideListItem?.elements?.map((item, index) => {
          // 文本
          if (item.type === 'Text') {
            return (
              <div
                onDoubleClick={() => {
                  doubleClick('Text', index);
                }}
                className={styles['slide-item']}
                key={item?.id}
                style={{
                  border: '1px solid #e8e8e8',
                  color: item?.fontColor || '#000000',
                  fontSize: `${item?.fontSize || 18}em`,
                  fontWeight: item?.fontWight || 800,
                  width: item?.blockWidth || 500,
                  height: item?.blockHeight || 250,
                  overflow: 'hidden',
                }}
              >
                {item?.content}
              </div>
            );
          }
          // 图片
          if (item.type === 'Image') {
            return (
              <div
                onDoubleClick={() => {
                  doubleClick('Image', index);
                }}
                className={styles['slide-item']}
                key={item.id}
              >
                <img
                  style={{
                    width: item?.blockWidth || 500,
                    height: item?.blockHeight || 250,
                  }}
                  src={item?.imageUrl}
                  alt={item?.describe}
                  // onError={(e) => {
                  //   const target = e.target;
                  //   target.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>';
                  // }}
                />
              </div>
            );
          }
          // 视频
          if (item.type === 'Video') {
            return (
              <div
                onDoubleClick={() => {
                  doubleClick('Video', index);
                }}
                className={styles['slide-item']}
                key={item?.videoUrl || item.id}
              >
                <video
                  style={{
                    border: '1px solid #e8e8e8',
                    verticalAlign: 'middle',
                    objectFit: 'fill',
                  }}
                  width={item?.blockWidth || 500}
                  height={item?.blockHeight || 250}
                  controls
                  // 阻止默认的双击全屏行为
                  controlsList="nofullscreen"
                >
                  <source src={item?.videoUrl || 250} type="video/mp4" />
                  Your browser does not support the video tag.
                </video>
              </div>
            );
          }
          // 代码
          if (item.type === 'Code') {
            return (
              <div
                onDoubleClick={() => {
                  doubleClick('Code', index);
                }}
                className={styles['slide-item']}
                key={item.id}
              >
                <div
                  className={styles['code-body']}
                  style={{
                    backgroundColor:
                      detectLanguage(item?.content) === 'Python'
                        ? '#eef6ff'
                        : detectLanguage(item?.content) === 'JavaScript'
                        ? '#fefce8'
                        : '#fbf5ff',
                  }}
                >
                  <div className={styles['code-title']}>{detectLanguage(item?.content)}</div>
                  <Editor
                    className={styles['code-content']}
                    value={item?.content}
                    highlight={(code) => highlight(code, languages.js, 'javascript')}
                    padding={4}
                    style={{
                      fontFamily: '"Fira code", "Fira Mono", monospace',
                      fontSize: item?.fontSize * 16 || 12,
                    }}
                    readOnly
                  />
                </div>
              </div>
            );
          }
          return null;
        })}
        <div style={{ position: 'absolute', bottom: 4, left: 4, color: '#bfbfbf', fontSize: 16 }}>
          {currentSlideIndex}
        </div>
      </div>
    </div>
  );
};

export default SlideContent;
